<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <title>工具</title>
    <link href="./sui.min.css" rel="stylesheet">
    <style type="text/css">
        .center {
            display: flex;
            justify-content: center;
            align-items: center;
        }
    </style>

    <!--<style type="text/css">-->
        <!--#result table {-->
        <!--border-collapse: collapse;-->
        <!--}-->

        <!--#result th, td {-->
        <!--border: solid 1px #6D6D6D;-->
        <!--padding: 5px 10px;-->
        <!--}-->
        <!--</style>-->
    </head>
    <body>
        <!-- 输入框 -->
        <div class="center" style="margin: 10px">
            <textarea id="testContentTextArea"
            style="height: 550px;width: 90%;white-space:nowrap; overflow:scroll;"
            class="input-xxlarge">
        </textarea>
        <!--562182447179002011+ 杜佳梦1+151-->
        <!--哈+哈3  +     561933613536183813 ＋  153 元 圆-->

        <!--561933613536183823-->
        <!--153-->

        <!--aa-->


        <!--152圆   +  铛铛2  +  561933613536183812-->
        <!--562207694202275312+ 我他娘的根本就不想用+381-->
        <!--bb-->
    </div>

    <!-- 处理按钮 -->
    <div class="center" style="text-align: center;padding:30px 30% 50px 30%;">
        <a onclick="onTextDataToTable()" class="sui-btn btn-block btn-xlarge btn-primary">处理</a>
    </div>

    <!-- 表格显示 -->
    <div>
        <table class="sui-table table-bordered">
            <thead>
                <tr id="tr">
                    <th>序号</th>
                    <th>＃原数据</th>
                    <th>名字</th>
                    <th>ID</th>
                    <th>价格</th>
                </tr>
            </thead>
            <tbody id="tbody">
            </tbody>
        </table>
    </div>

    <div id="tip" style="color: red;margin-left: 10px"></div>

    <!-- 操作按钮组 -->
    <div class="center" style="text-align: center;margin:30px 0px 60px 0px">
        <a onclick="onCopyAllContent()" class="sui-btn btn-xlarge btn-success"
        style="margin-right: 20px"
        id="btnAllCopy">整体拆分复制</a>
        <a onclick="onCopyContent()" class="sui-btn btn-xlarge btn-success" style="margin-right: 20px"
        id="btnCopy">表格拆分复制</a>
        <a onclick="onExportExcel()" class="sui-btn btn-xlarge btn-info" id="btnExcel">表格导出excel</a>
    </div>

    <div class="center" style="margin: 10px">
        <textarea id="ttCal"
        style="height: 300px;width: 50%;white-space:nowrap; overflow:scroll;"
        class="input-xxlarge">

    </textarea>
</div>

<div class="center" style="text-align: center;margin:30px 0px 60px 0px">
    <a onclick="onCopyCal()" class="sui-btn btn-xlarge btn-success" style="margin-right: 20px"
    id="btnCal">计算且复制</a>
</div>
<div id="calResult" class="center" style="margin-top:-20px;margin-bottom: 40px;font-size: 20px"/>


<!--<div class="excelTable">-->
    <!--<p>结果输出：（下面表格可直接编辑导出）</p>-->
    <!--<div id="result" contenteditable style="margin-left: 30px"></div>-->
    <!--</div>-->

</body>

<script type="text/javascript" src="./jquery.min.js"></script>
<script type="text/javascript" src="./sui.min.js"></script>
<script type="text/javascript" src="./xlsx.full.min.js"></script>

<script type="text/javascript">

    //====click =========================================
    function onCopyCal() {
        var sourceContent = getTextAreaData();
        var deleBlankArray = deletBlankRows(sourceContent);//删除空白行
        spliteDataSpace(deleBlankArray);//分割字符，并计算
    }

    //====util =========================================
    function spliteDataSpace(sourceContent) {
        console.warn("---每行数字数组：");
        var arrayBySpace = [];
        var isBreak = false;
        var arrayByspaceWithCheck = [];
        var subNumber = 0;
        var index = 0;
        for (var i = 0; i < sourceContent.length; i++) {
            var contentByRow = sourceContent[i].trim();
            var numberByRow = contentByRow.split(/\s+/);
            console.log("---第" + (i + 1) + "行");
            console.log(numberByRow);
            arrayBySpace.push(numberByRow);
        }

        for (var i = 0; i < arrayBySpace.length; i++) {
            var numberByRow = arrayBySpace[i];
            for (var j = 0; j < numberByRow.length; j++) {
                var spaceNumber = numberByRow[j];
                var isNumber = (/^[\.\d]*$/).test(spaceNumber);
                if (isNumber) {
                    subNumber = subNumber + parseFloat(spaceNumber);
                    arrayByspaceWithCheck[index] = spaceNumber;
                } else {
                    isBreak = true;
                    arrayByspaceWithCheck[index] = spaceNumber + "❎";
                }
                ++index;
            }
        }

        console.warn("---最终要参与计算的值：");
        console.log('值：' + arrayByspaceWithCheck);
        if (isBreak) {
            var tip = "其中包含非数字字符，请改正，再重新计算！";
            new Toast({context: $('body'), message: tip}).show();
            console.error(tip);
            document.getElementById('calResult').innerText = tip + "\n\n" + arrayByspaceWithCheck;
        } else {
            var finalSubNumber = subNumber.toFixed(2);
            console.warn("---计算总和：");
            console.log('总和：' + finalSubNumber);
            document.getElementById('calResult').innerText = "求和结果：" + finalSubNumber + "\n\n" + arrayByspaceWithCheck;
            onCopySubContent(finalSubNumber);
        }

    }

    function getTextAreaData() {
        sourceContent = $("#ttCal").val();//输入框中的数据
        console.warn("---①初始数据：");
        console.log(sourceContent);
        //eg.[ "562182447179002011+ 杜佳梦1+151", "562182447179002022+ 杜佳梦2+152"],注意：此方法在有空行的输入框数据时，会出现重复数据
        sourceStrArray = $("#ttCal").val().split("\n");
        console.warn("---②初始数据分割成数组：\n");
        console.log(sourceStrArray);
        return sourceStrArray;
    }

    function deletBlankRows(ssArray) {
        for (var i = ssArray.length - 1; i >= 0; i--) {
            if (ssArray[i].replace(/\s*/g, "").trim() == "") {
                ssArray.splice(i, 1);        //执行后aa.length会减一
                // ssArray.remove(i);
                console.log("第" + (i + 1) + "为空白行，现已优化掉");
            }
        }
        return ssArray;
    }

    function onCopySubContent(copyContents) {
        if (!((copyContents + "").length > 1)) {
            new Toast({context: $('body'), message: '暂无数据可拷贝'}).show();
        } else {
            console.warn("最终粘贴板的数据：");
            console.log(copyContents);
            copyText(copyContents, function () {
                new Toast({context: $('body'), message: '总和：' + copyContents + "，复制成功"}).show();
            })
        }
    }


    Array.prototype.remove = function (dx) {

        if (isNaN(dx) || dx > this.length) {
            return false;
        }

        for (var i = 0, n = 0; i < this.length; i++) {
            if (this[i] != this[dx]) {
                this[n++] = this[i];
            }
        }
        this.length -= 1;
    };


</script>

<script type="text/javascript">
    var copyNames = "";//最终要拷贝的名字集合
    var copyIds = "";//最终要拷贝的id集合
    var copyPrices = "";//最终要拷贝的prices集合
    var excel = [];//最终excel要打印的数据
    var splitSourceArrayArray = [];//[[name,name,name],[price,price,price],[id,id,id]]

    //====click =========================================
    function onExportExcel() {
        if (excel.length == 0) {
            new Toast({context: $('body'), message: '暂无数据可导出'}).show();
        } else {
            // var excelTitle = ['姓名', 'ID', 'Price'];
            // excel.unshift(excelTitle);//添加excele表头
            console.warn("\n\n最终excel表数据：");
            console.log(excel);
            var sheet = XLSX.utils.aoa_to_sheet(excel);
            // 设置exceal列宽度
            sheet["!cols"]=[
                    { wch: 25 }, // 第一列
                    { wch: 25 }, // 第二列
                    { wch: 10 }  // 第三列
                ]
            openDownloadDialog(sheet2blob(sheet), "纪梵" + getCurrentTime() + "退款单.xlsx");
            new Toast({context: $('body'), message: '导出成功'}).show();
        }
    }

    function onCopyAllContent() {
        if (copyNames == "") {
            new Toast({context: $('body'), message: '暂无数据可拷贝'}).show();
        } else {
            // var copyContents = copyNames + "\n\n" + copyIds + "\n\n" + copyPrices;
            // console.warn("最终粘贴板的数据：");
            // console.log(copyContents);
            copyText(splitSourceArray(), function () {
                new Toast({context: $('body'), message: '复制成功'}).show();
            })
        }
    }


    function onCopyContent() {
        if (copyNames == "") {
            new Toast({context: $('body'), message: '暂无数据可拷贝'}).show();
        } else {
            var copyContents = copyNames + "\n\n" + copyIds + "\n\n" + copyPrices;
            console.warn("最终粘贴板的数据：");
            console.log(copyContents);
            copyText(copyContents, function () {
                new Toast({context: $('body'), message: '复制成功'}).show();
            })
        }
    }

    function onTextDataToTable() {
        initOptionButtonData();//粘贴板和导出的excel内容要重置，避免上一个操作的脏数据污染

        console.log("====🦁一、获取数据源：多行集合 =========================================");
        var sourceContent;
        var sourceStrArray;
        getTextAreaData();

        console.log("\n\n\n\n====🦁二、数据处理：分三个数组 =========================================");
        var oneRowArray;//每一行数据+分割的数组:eg.[642316482729713759,张三8835,381]
        var preRowArray;
        var sourceArrayArray = [];//将每一行数据放到该数组中：eg.[rowArray1,rowArray2]
        var oneRowStr;//每一行的数据:eg. 642316482729713759+张三8835+381

        //遍历得到的格子数据，最终方法这三个分类中
        var names = [];
        var tbIds = [];
        var prices = [];
        var phoneNumber = [];
        var realName = [];

        //删除重复行
        sourceStrArray = clearRepet();
        //删除空白行；遍历删除，会改变索引，既要倒序删除
        deletBlankRow();

        initTbIdsAndPricesData();
        initNamesData();


        console.log("\n\n\n\n====🦁三、数据显示：数组分组显示 =========================================");
        printSourceStrArrayNamesTbIdsPrices();
        //每次点击，删除原来有td的tr，插入空的tr
        initTable(names);
        //构建table，赋值粘贴板和execl数据
        buildTableAndInitCopyExcelData();

        //======methed-util========================
        function getTextAreaData() {
            sourceContent = $("#testContentTextArea").val();//输入框中的数据
            console.warn("---①初始数据：");
            console.log(sourceContent);
            //eg.[ "562182447179002011+ 杜佳梦1+151", "562182447179002022+ 杜佳梦2+152"],注意：此方法在有空行的输入框数据时，会出现重复数据
            sourceStrArray = $("#testContentTextArea").val().split("\n");
            console.warn("---②初始数据分割成数组：\n");
            console.log(sourceStrArray);
        }

        function clearRepet() {
            console.warn("---①优化源数据重复和空白行：");
            var tempSourceArray = [];
            //去重（1.本身有重复行；2.用\n做分割形成content时可能会导致重复行）;下面删除空白行是倒序，这里最好用正序(不然显示的数据时倒序)，既两个分开遍历
            for (var i = 0; i < sourceStrArray.length; i++) {
                if (!tempSourceArray.contains(sourceStrArray[i])) {
                    tempSourceArray.push(sourceStrArray[i]);
                } else {
                    console.log("第" + (i + 1) + "为重复行，现已优化掉");
                    // new Toast({context: $('body'), message: '有重复行，已优化'}).show();
                }
            }
            return tempSourceArray;
        }

        function deletBlankRow() {

            for (var i = sourceStrArray.length - 1; i >= 0; i--) {
                if (sourceStrArray[i].replace(/\s*/g, "").trim() == "") {
                    sourceStrArray.splice(i, 1);
                }
                // if (sourceStrArray[i].trim() == "") {
                //     sourceStrArray.remove(i);
                //     console.log("第" + (i + 1) + "为空白行，现已优化掉");
                // }
            }
        }

        function initTbIdsAndPricesData() {
            console.warn("\n---②提取price和tbid数据，同时将price和tbid做''标记处理");
            console.log("去重后的原始数据：");
            console.log(sourceStrArray);
            console.log("\n\n");
            for (var i = 0; i < sourceStrArray.length; i++) {
                oneRowStr = sourceStrArray[i].replaceAll("＋", "+").trim();
                oneRowStr = oneRowStr.replace(/\s+/g, "");
                oneRowStr = oneRowStr.replaceAll(" ＋", "+").trim();
                oneRowStr = oneRowStr.replaceAll("＋ ", "+").trim();
                oneRowStr = oneRowStr.replaceAll(" ＋ ", "+").trim();
                oneRowStr = oneRowStr.replaceAll(" +", "+").trim();
                oneRowStr = oneRowStr.replaceAll(" + ", "+").trim();

                oneRowStr = oneRowStr.replaceAll("十", "+").trim();
                oneRowStr = oneRowStr.replaceAll("➕", "+").trim();

                oneRowStr = oneRowStr.replace("+ ", "+").trim();//replaceAll在该替换项会报错，因为不影响使用，暂时还是用replace

                // oneRowStr = oneRowStr.replace(" ＋", "+").trim();
                // oneRowStr = oneRowStr.replace(" ＋", "+").trim();

                if (true) {//去掉空行+格式不正确的行：原来是每行必须大于18个字符，这里不限制了
                    oneRowArray = oneRowStr.split("+");//每一行数据数组：eg.[tb212547948,561897069452473702,381]
                    oneRowArrayCopy = oneRowStr.split("+");//每一行数据数组：eg.[tb212547948,561897069452473702,381]
                    splitSourceArrayArray.push(oneRowArrayCopy);
                    console.log("去重后的第" + (i + 1) + "行数据分段数组：");
                    console.log(oneRowArray);
                    if(typeof(preRowArray)!="undefined"&&oneRowArray.length!=preRowArray.length){
                        document.getElementById('tip').innerText ="请重点检查第"+i +"行，其次检查第"+(i-1)+"和"+(i+1)+"行";
                    }
                    preRowArray=oneRowArray;
                    var isEnterPrices = false;//是否进入过price.push
                    var isEnterTbids = false;//是否进入过tbIds.push
                    var isEnterRealName = false;
                    var isEnterPhoneNumber = false;
                    for (var index2 = 0; index2 < oneRowArray.length; index2++) {
                        //每一行中的每个格子数据：eg.tb212547948；561897069452473702；381
                        var oneGridStr = oneRowArray[index2].trim();

                        //获取prices数据：这里虽然是直接替换了元/圆，但是只是针对拷贝数据，没有动元数据rowArray（下面同时匹配是4位一下的数据，才会动元数据）
                        var OneGridDataTrim = oneGridStr.replaceAll("元", "").replaceAll("圆", "").trim();

                        var isNumber = (/^[\.\d]*$/).test(OneGridDataTrim);//是否是数字,小数也算（不然：6abc6,这样经过parseInt也会转成数字）
                        if (isNumber && parseInt(OneGridDataTrim) >= 0 && parseInt(OneGridDataTrim) < 10000) {
                            prices.push(OneGridDataTrim);
                            oneRowArray[index2] = "";//prices已备份数据，将原有格子数据清空""，以便标记出name
                            isEnterPrices = true;
                        }
                        // if (/^[0-9]+$/.test(OneGridDataTrim) && OneGridDataTrim.length < 4) {//去掉元/圆后，还全是数字且是在1000以内，既基本就是金额了。todo：暂时考虑1000以内的金额
                        //     prices.push(OneGridDataTrim);
                        //     oneRowArray[index2] = "";//prices已备份数据，将原有格子数据清空""，以便标记出name
                        //     isEnterPrices = true;
                        // }

                        // if (!isNumber && 0 < OneGridDataTrim.length < 4) {
                        //     realName.push(OneGridDataTrim);
                        //     oneRowArray[index2] = "";
                        //     isEnterRealName = true;
                        // }

                        // if (isPoneAvailable(OneGridDataTrim)) {
                        //     phoneNumber.push(OneGridDataTrim)
                        //     oneRowArray[index2] = "";
                        //     isEnterPhoneNumber = true;
                        // }

                        //获取tbIds数据：长度为18且全是数字的既认为是tbIds
                        if ((OneGridDataTrim.length == 18 || OneGridDataTrim.length == 19) && /^[0-9]+$/.test(OneGridDataTrim)) {
                            tbIds.push(OneGridDataTrim);
                            oneRowArray[index2] = "";
                            isEnterTbids = true;
                        }


                        if (index2 == oneRowArray.length - 1) {
                            if (!isEnterPrices) {
                                prices.push("❎(金额不是小于4位的数)");
                            }
                            if (!isEnterTbids) {
                                tbIds.push("❎(长度不是18/19位)");
                            }
                            // if (!isEnterRealName) {
                            //     realName.push("❎(长度不是0-3位)")
                            // }
                            // if (isEnterPhoneNumber) {
                            //     phoneNumber.push("❎(长度不是11位数字)")
                            // }
                            isEnterPhoneNumber = false;
                            isEnterPrices = false;
                            isEnterTbids = false;
                            isEnterRealName = false;
                        }
                    }
                    sourceArrayArray.push(oneRowArray);
                }
            }

            console.log("\n\n最终给tbIds的数据：");
            console.log(tbIds);
            console.log("最终给prices的数据：");
            console.log(prices);
            console.log("最终给realName的数据：");
            console.log(realName);
            console.log("最终给phoneNumber的数据：");
            console.log(phoneNumber);
            console.log("最终+号分割后的数组:oneRowArrayCopy")
            console.log(oneRowArrayCopy)
        }

        function initNamesData() {
            console.warn("\n\n---③提取name数据：");
            console.log("上一步将price和tbid做''标记处理后的源数据：");
            console.log(sourceArrayArray);

            for (var i = 0; i < sourceArrayArray.length; i++) {
                var newOneRowArray = sourceArrayArray[i];//每一行数据数组且price和id都已经置空：eg.[tb212547948,"",""]
                var strName = "";
                for (var index = 0; index < newOneRowArray.length; index++) {
                    var newTrimOneGridData = newOneRowArray[index].trim();
                    //处理name中有+的情况
                    if (strName != "" && newTrimOneGridData != "") {
                        strName = strName + "+" + newTrimOneGridData;
                    } else {
                        strName = strName + newTrimOneGridData;
                    }
                }
                if (strName == "") {
                    strName = "❎";
                }
                // console.log("给names的数据："+newTrimOneGridData);
                names.push(strName);
            }
            console.log("最终给names的数据：");
            console.log(names);
        }

        function printSourceStrArrayNamesTbIdsPrices() {
            console.warn("①sourceStrArray，names，tbIds，prices")
            console.log("---------sourceStrArray--->");
            console.log(sourceStrArray);
            console.log("---------names--->");
            console.log(names);
            console.log("---------tbIds--->");
            console.log(tbIds);
            console.log("---------prices--->");
            console.log(prices);
        }

        function buildTableAndInitCopyExcelData() {
            console.warn("\n\n③新表格html构建完成\n\n");
            for (var i = 0; i < names.length; i++) {
                // if(typeof(names[i])=="undefined"||typeof(tbIds[i])=="undefined"||typeof(prices[i])=="undefined"){
                //   new Toast({context:$('body'),message:"第"+(i+1)+'行格式不正确，请注意调整！'}).show();
                //     // alert("格式不正确，请注意调整！");
                //   }
                var number = "<td>" + (i + 1) + "</td>";
                var ct = "<td>" + sourceStrArray[i] + "</td>";
                var ne = "<td>" + names[i] + "</td>";
                var tbId = "<td>" + tbIds[i] + "</td>";
                var price = "<td>" + prices[i] + "</td>";
                var tableTr = number + ct + ne + tbId + price;
                $("#tr" + i).append(tableTr);

                console.log("最终表格：第" + (i + 1) + "行数据：\n" + tableTr);
                var onwRowData = new Array(names[i], tbIds[i], prices[i]);
                excel.push(onwRowData);

                if (copyNames == "") {
                    copyNames = copyNames + names[i];
                } else {
                    copyNames = copyNames + "\n" + names[i];
                }
                if (copyIds == "") {
                    copyIds = copyIds + tbIds[i];
                } else {
                    copyIds = copyIds + "\n" + tbIds[i];
                }
                if (copyPrices == "") {
                    copyPrices = copyPrices + prices[i];
                } else {
                    copyPrices = copyPrices + "\n" + prices[i];
                }
            }
        }
    }

    //====test =========================================

    function onshowExcelTest() {
        if (excel.length == 0) {
            new Toast({context: $('body'), message: '暂无数据可导出'}).show();
        } else {
            // var excelTitle = ['姓名', 'ID', 'Price'];
            // excel.unshift(excelTitle);//添加excele表头
            console.warn("\n\n最终excel表数据：");
            console.log(excel);
            var sheet = XLSX.utils.aoa_to_sheet(excel);
            readWorkbook(sheet);
            // openDownloadDialog(sheet2blob(sheet), "纪梵" + getCurrentTime() + "退款单.xlsx");
            new Toast({context: $('body'), message: '导出成功'}).show();
        }
    }

    function readWorkbook(worksheet) {
        var csv = XLSX.utils.sheet_to_csv(worksheet);
        document.getElementById('result').innerHTML = csv2table(csv);
    }


    // 将csv转换成简单的表格，会忽略单元格合并，在第一行和第一列追加类似excel的索引
    function csv2table(csv) {
        var html = '<table>';
        var rows = csv.split('\n');
        rows.pop(); // 最后一行没用的
        rows.forEach(function (row, idx) {
            var columns = row.split(',');
            columns.unshift(idx + 1); // 添加行索引
            if (idx == 0) { // 添加列索引
                html += '<tr>';
                for (var i = 0; i < columns.length; i++) {
                    html += '<th>' + (i == 0 ? '' : String.fromCharCode(65 + i - 1)) + '</th>';
                }
                html += '</tr>';
            }
            html += '<tr>';
            columns.forEach(function (column) {
                html += '<td>' + column + '</td>';
            });
            html += '</tr>';
        });
        html += '</table>';
        return html;
    }


    //====util =========================================
    function clearTr() {
        var tr = document.getElementsByTagName('tbody')[0].getElementsByTagName('tr');
        for (var i = tr.length - 1; i >= 0; i--) {
            $("#tr" + i).remove();
        }

    }

    function initTable(names) {
        console.warn("\n\n②完成Table表重置\n\n");
        //删tr结构时，最好是根据tbody动态计算节点个数
        clearTr();
        var tempContent = "";
        for (var i = 0; i < names.length; i++) {
            // if (typeof($("#tr" + i)) != "undefined") {
            //     $("#tr" + i).remove();
            // }
            var tr = '<tr id="tr' + i + '"></tr>'
            tempContent = tempContent + tr;

        }
        $("#tbody").append(tempContent); //将新创建的div节点插入到nav容器的内容底部
    }

    function copyText(text, callback) { // text: 要复制的内容， callback: 回调
        var tag = document.createElement('textarea');
        tag.value = text;
        document.getElementsByTagName('body')[0].appendChild(tag);
        tag.select();
        document.execCommand('copy');
        tag.remove();
        if (callback) {
            callback(text)
        }
    }

    function initOptionButtonData() {
        excel = [];
        copyNames = "";
        copyIds = "";
        copyPrices = "";
        splitSourceArrayArray = [];//重置
        document.getElementById('tip').innerText = ""
    }

    function splitSourceArray() {
        //将[[name,name,name],[price,price,price],[id,id,id]]，转成换行后的string
        var columnsNumber = splitSourceArrayArray[0].length;
        var resultArray = [];
        for (var i = 0; i < columnsNumber; i++) {
            resultArray[i] = [];
        }
        for (var i = 0; i < splitSourceArrayArray.length; i++) {
            var singleArray = splitSourceArrayArray[i];
            for (var j = 0; j < singleArray.length; j++) {
                resultArray[j][i] = singleArray[j];
                // resultArray[j]=singleArray[j];
            }
        }
        var resultString = "";
        for (var i = 0; i < resultArray.length; i++) {
            var oneRowString = "";
            var oneRowArray = resultArray[i];
            for (var j = 0; j < oneRowArray.length; j++) {
                var str = oneRowArray[j];
                if (typeof (str) == "undefined") {
                    str = "❎";
                }
                oneRowString = oneRowString + str + "\n";
            }
            resultString = resultString + oneRowString + "\n\n";
        }
        console.warn("最终粘贴板的数据：");
        console.log(resultString);
        return resultString;

    }

    function isPoneAvailable(poneInput) {
        var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
        if (!myreg.test(poneInput)) {
            return false;
        } else {
            return true;
        }
    }

    //====toast =========================================
    var Toast = function (config) {
        this.context = config.context == null ? $('body') : config.context;//涓婁笅鏂�
        this.message = config.message;//鏄剧ず鍐呭
        this.time = config.time == null ? 3000 : config.time;//鎸佺画鏃堕棿
        this.left = config.left;//璺濆鍣ㄥ乏杈圭殑璺濈
        this.top = config.top;//璺濆鍣ㄤ笂鏂圭殑璺濈
        this.init();
    }
    var msgEntity;
    Toast.prototype = {
        init: function () {
            $("#toastMessage").remove();
            var msgDIV = new Array();
            msgDIV.push('<div id="toastMessage">');
            msgDIV.push('<span>' + this.message + '</span>');
            msgDIV.push('</div>');
            msgEntity = $(msgDIV.join('')).appendTo(this.context);
            var left = this.left == null ? this.context.width() / 2 - msgEntity.find('span').width() / 2 - 20 : this.left;
            //var top = this.top == null ? '20px' : this.top;
            var bottom = this.bottom == null ? '100px' : this.bottom;
            msgEntity.css({
                position: 'absolute',
                bottom: bottom,
                'z-index': '99',
                left: left,
                'background-color': 'black',
                color: 'white',
                'font-size': '14px',
                // 'font-family': '寰蒋闆呴粦',
                'border-radius': '5px',
                padding: '10px',
                margin: '10px'
            });
            msgEntity.hide();
        },
        show: function () {
            msgEntity.fadeIn(this.time / 2);
            msgEntity.fadeOut(this.time / 2);
        }

    }

    //====excel =========================================
    /**
     * 通用的打开下载对话框方法，没有测试过具体兼容性
     * @param url 下载地址，也可以是一个blob对象，必选
     * @param saveName 保存文件名，可选
     */
     function openDownloadDialog(url, saveName) {
        if (typeof url == 'object' && url instanceof Blob) {
            url = URL.createObjectURL(url); // 创建blob地址
        }
        var aLink = document.createElement('a');
        aLink.href = url;
        aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
        var event;
        if (window.MouseEvent) event = new MouseEvent('click');
        else {
            event = document.createEvent('MouseEvents');
            event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        }
        aLink.dispatchEvent(event);
    }

    // 将一个sheet转成最终的excel文件的blob对象，然后利用URL.createObjectURL下载
    function sheet2blob(sheet, sheetName) {
        sheetName = sheetName || 'sheet1';
        var workbook = {
            SheetNames: [sheetName],
            Sheets: {}
        };
        workbook.Sheets[sheetName] = sheet;
        // 生成excel的配置项
        var wopts = {
            bookType: 'xlsx', // 要生成的文件类型
            bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
            type: 'binary'
        };
        var wbout = XLSX.write(workbook, wopts);
        var blob = new Blob([s2ab(wbout)], {type: "application/octet-stream"});

        // 字符串转ArrayBuffer
        function s2ab(s) {
            var buf = new ArrayBuffer(s.length);
            var view = new Uint8Array(buf);
            for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
                return buf;
        }

        return blob;
    }

    function getCurrentTime() {
        var date = new Date();
        //年
        var year = date.getFullYear();
        //月
        var month = date.getMonth() + 1;
        //日
        var day = date.getDate();
        //时
        var hh = date.getHours();
        //分
        var mm = date.getMinutes();
        //秒
        var ss = date.getSeconds();
        var rq = year + "年" + month + "月" + day + "日";
        return rq;
    }

    //====数组功能扩展 =========================================
    Array.prototype.remove = function (dx) {

        if (isNaN(dx) || dx > this.length) {
            return false;
        }

        for (var i = 0, n = 0; i < this.length; i++) {
            if (this[i] != this[dx]) {
                this[n++] = this[i];
            }
        }
        this.length -= 1;
    };

    Array.prototype.contains = function (obj) {
        var i = this.length;
        while (i--) {
            if (this[i] === obj) {
                return true;
            }
        }
        return false;
    }

    String.prototype.replaceAll = function (s1, s2) {
        return this.replace(new RegExp(s1, "gm"), s2);
    }

    window.onerror = function(errorMessage, scriptURI, lineNumber,columnNumber,errorObj) { 
        // new Toast({context: $('body'), message: '暂无数据可导出'}).show();
        document.getElementById('tip').innerText = errorMessage;
        // console.log("错误信息：" , errorMessage); 
        // console.log("出错文件：" , scriptURI); 
        // console.log("出错行号：" , lineNumber); 
        // console.log("出错列号：" , columnNumber); 
        // console.log("错误详情：" , errorObj); 
    } 

    //sub：将源数据，整理成sourceStrArray、names、tbIds、prices三个数组

    //特定测试数据：
    // 562182447179002011+ 杜佳梦1+151
    // 哈+哈3  +     561933613536183813 ＋  153 元 圆
    //
    // 561933613536183823
    // 153
    //
    // aa
    //
    //
    // 152圆   +  铛铛2  +  561933613536183812
    // 562207694202275312+ 我他娘的根本就不想用+381
    // bb

    // 562207694202275312+ 我他娘的根本就不想用+381
    // 642316482729713759+ zhanghaoyang8835+381
    // t_1489105952578_0658+ 558259397961714790+381
    // 桃花依旧人事全非11+381+562018540887565014
    // 641976928461584954  +   儒雅饭饭米   +381
    // 558249381062589889+胡鹤琪+381
    // 642077283981726865+一起去购物_65+381
    // 642069987610199131+ 米妞嗨起来呀+381
    // 558290950262765396+381+我想去旅行726
    // 561935661809363721+好佳媛+381
    // 642015234316161643+tb483768742+381
    // 雨中泪流诳彩+641858912119313828+381元
    // 田行江+ 641996803399011483+381
    // 558188836179257195+ 活泼的雨涵+ 381
    // tb212547948+561897069452473702+381

    //三方库：
    // [如何使用JavaScript实现纯前端读取和导出excel文件 - 我是小茗同学 - 博客园] (https://www.cnblogs.com/liuxianan/p/js-excel.html)

</script>
</html>



